<!-- 教师端统计分析个人模块 -->
 <!-- 注意：若有重名的学生，雷达图会将其两个数据合并，
            状态：未解决
            解决思路：雷达图 series 用学号作为唯一 key，tooltip 和 legend 显示姓名-->
<template>
  <div>
    <!-- <div class="id-select"> -->
    <el-form :model="form" ref="formRef" label-width="80px">
      <el-row :gutter="20" class="form-row">

        <!-- 学生学号 -->
        <el-col :span="5">
          <el-form-item label="学生学号">
            <el-select
              class="select"
              v-model="form.account"
              filterable
              clearable
              placeholder="请选择学生学号"
              @change="onAccountChange"
            >
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 学生姓名 -->
        <el-col :span="5">
          <el-form-item label="学生姓名">
            <el-select
              class="select"
              v-model="form.student"
              filterable
              clearable
              placeholder="请选择学生姓名"
              @change="onStudentChange"
            >
              <el-option
                v-for="item in options2"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 毕业年级
        <el-col :span="5">
          <el-form-item label="毕业年级">
            <div>
              {{ form.grade}}
            </div>
          </el-form-item>
        </el-col> -->

        <!-- 按钮
        <el-col :span="6" class="button-col">
          <el-form-item label="">
            <el-button type="primary" @click="onSearch">搜索</el-button>
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
      
    <!-- </div> -->
    <div class="score-table">
      <div class="new-score">最新提交论文评分</div>
      <!-- <el-table :data="tableData" class="score">
        <el-table-column prop="zscore" label="总分"/>
        <el-table-column prop="gscore" label="工作量评分"/>
        <el-table-column prop="nscore" label="内容组织能力评分"/>
        <el-table-column prop="wscore" label="文献调研能力评分"/>
        <el-table-column prop="lscore" label="逻辑结构能力评分"/>
      </el-table> -->
      <div class="paper-score">
        <div class="total">
          <div class="total-title">总分</div>
          <div class="total-score">{{overview.totalScore}}</div>
        </div>
        <div class="topicSignificance">
          <div class="total-title">选题意义评分</div>
          <div class="total-score">{{overview.firstScore}}</div>
        </div>
        <div class="writingSchedule">
          <div class="total-title">写作安排评分</div>
          <div class="total-score">{{overview.secondScore}}</div>
        </div>
        <div class="logicalStructure">
          <div class="total-title">逻辑构建评分</div>
          <div class="total-score">{{overview.thirdScore}}</div>
        </div>
        <div class="professionalAbility">
          <div class="total-title">专业能力评分</div>
          <div class="total-score">{{overview.fourthScore}}</div>
        </div>
        <div class="academicNorms">
          <div class="total-title">学术规范评分</div>
          <div class="total-score">{{overview.fifthScore}}</div>
        </div>
          <!-- <el-table-column prop="avgTotal" label="平均总评分"/>
          <el-table-column prop="maxTotal" label="最高总评分"/>
          <el-table-column prop="minTotal" label="最低总评分"/>
          <el-table-column prop="workload" label="工作量评分"/>
          <el-table-column prop="content" label="内容组织评分"/>
          <el-table-column prop="research" label="文献调研评分"/>
          <el-table-column prop="logic" label="逻辑结构评分"/> -->
      </div>
    </div>
    <div class="score-compare">
      <div class="history-score">历史版本评分对比</div>
      <div ref="radarChart" class="radar-chart"></div>
    </div>
    <div class="score-compare">
      <div class="history-score">历史版本评分对比</div>
      <div ref="multiLineChart" class="multi-line-chart"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { ElMessage } from 'element-plus';
import { reactive } from 'vue'
import {
getAllStudentsByTeacher,
getAllPaperByStudent,
getTeacherSelfPaperScore
} from "@/api/teacher.js";


const form = reactive({
  account:'',
  student: '',
  grade:''
})
const overview = ref({
  totalScore:0,
  firstScore:0,
  secondScore:0,
  thirdScore:0,
  fourthScore:0,
  fifthScore:0
})
const options1 = ref([]) // 学号下拉
const options2 = ref([]) // 姓名下拉
const studentMap = ref({}); // key: 学号，value: 姓名

const userId = localStorage.getItem('userId')


//下拉框
const getStudent = async () =>{
  try{
    
    console.log(userId)
    const res = await getAllStudentsByTeacher(userId) // 作为入参
    console.log("学生数据：",res.data)
    
    // 学号下拉
    options1.value = res.data.map(y => ({
      label: y.id,
      value: y.id
    }))

    // 姓名下拉
    options2.value = res.data.map(y => ({
      label: y.name,
      value: y.name
    }))
    


    // 默认选中第一个
    if (res.data.length > 0) {
      form.account = res.data[0].id
      form.student = res.data[0].name
      form.grade = res.data[0].grade
    }
    // 学号-姓名映射
    studentMap.value = {};
    res.data.forEach(item => {
      studentMap.value[item.id] = item.name;
    });

    // ⭐ 默认加载第一个学生的图表数据
    await onSearch();

   }catch(error){
     ElMessage.error('统计分析学号姓名获取失败')
   }
}


// const allData = {
//   '001': {
 
//     // tableData: [
//     //   {zscore: '85', gscore: '83', nscore: '95', wscore: '89', lscore: '79'}
//     // ],
//     radarData: [
//       { value: [82, 84, 73,73, 74, 76], name: '第一次提交' },
//       { value: [71, 86, 78,77, 78, 82], name: '第二次提交' },
//       { value: [86, 92, 85,63, 85, 87], name: '第三次提交' },
//       { value: [96, 96, 92,78, 90, 93], name: '第四次提交' },
//     ],
//     lineData: {
//       xAxis: ['第一次提交', '第二次提交', '第三次提交', '第四次提交'],
//       series: [
//         { name: '总评分', data: [82, 71, 86, 96] },
//         { name: '选题意义评分', data: [84, 86, 92, 96] },
//         { name: '写作安排评分', data: [73, 78, 85, 92] },
//         { name: '逻辑构建评分', data: [74, 78, 85, 90] },
//         { name: '专业能力评分', data: [77, 72, 82, 98] },
//         { name: '学术规范评分', data: [76, 82, 87, 93] }
//       ]
//     }
//   },
// }


// 搜索学生论文数据（改成独立函数）
const onSearch = async () => {
  try {
    if (!form.account) {
      ElMessage.warning('请先选择学生');
      return;
    }

    const viewdata = await getTeacherSelfPaperScore(form.account);
    console.log("概述数据：", viewdata.data);

    const res = await getAllPaperByStudent(form.account);
    console.log("论文数据：", res.data);

    if (!res.data || res.data.length === 0) {
      ElMessage.warning('该学生暂无论文数据');
      return;
    }
    
    if (!viewdata.data) {
      ElMessage.warning('该学生暂无论文概述数据');
      overview.value = {
        totalScore: 0,
        firstScore: 0,
        secondScore: 0,
        thirdScore: 0,
        fourthScore: 0,
        fifthScore: 0
      };
    } else {
      overview.value = viewdata.data;
      
    }


    // 转换成 radarData
    const radarData = res.data.map(item => ({
      value: [
        item.totalScore,
        item.firstScore,
        item.secondScore,
        item.thirdScore,
        item.fourthScore,
        item.fifthScore
      ],
      name: item.submitName
    }));

  // 转换成 lineData
  const lineData = {
    xAxis: res.data.map((_, index) => `第${index + 1}次提交`),  // ⭐ 用序号替代
    series: [
      { name: '总评分', data: res.data.map(item => item.totalScore) },
      { name: '选题意义评分', data: res.data.map(item => item.firstScore) },
      { name: '写作安排评分', data: res.data.map(item => item.secondScore) },
      { name: '逻辑构建评分', data: res.data.map(item => item.thirdScore) },
      { name: '专业能力评分', data: res.data.map(item => item.fourthScore) },
      { name: '学术规范评分', data: res.data.map(item => item.fifthScore) },
    ]
  };

    updateRadarChart(radarData);
    updateLineChart(lineData);
  } catch (error) {
    ElMessage.error('获取论文数据失败');
  }
};

//实现学号和姓名两个下拉框联动
const onAccountChange = (account) => {
  form.student = studentMap.value[account] || '';

  onSearch(); // 选择学号后触发搜索
}

const onStudentChange = (name) => {
  // 根据姓名查对应学号
  const account = Object.keys(studentMap.value).find(key => studentMap.value[key] === name);
  form.account = account || '';
  onSearch(); // 选择姓名后触发搜索
}
const input = ref('');
const radarChart = ref(null);
const multiLineChart = ref(null);
let chartInstance = null;
let LineInstance = null;



const updateRadarChart = (data) => {
  const option = {
    series: [{
      data: data
    }]
  };
  chartInstance.setOption(option);
};

const updateLineChart = (data) => {
  // 定义颜色集合
  const colors = ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'];
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: data.series.map(item => item.name),
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: data.xAxis
    },
    yAxis: {
      type: 'value'
    },
    series: data.series.map((item, index) => ({
      name: item.name,
      type: 'line',
      smooth: true,
      data: item.data,
      lineStyle: {
        width: 3,
        color: colors[index % colors.length]
      },
      symbol: 'circle',
      symbolSize: 8,
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: `${colors[index % colors.length]}80` },
          { offset: 1, color: `${colors[index % colors.length]}10` }
        ])
      },
      emphasis: {
        focus: 'series'
      }
    }))
  };
  
  LineInstance.setOption(option);
};
const initRadarChart = () => {
  chartInstance = echarts.init(radarChart.value);
  const option = {
    tooltip: {},
    legend: {
      data: [],
      bottom: 10
    },
    radar: {
      indicator: [
        { name: '总评分', max: 100 },
        { name: '选题意义评分', max: 100 },
        { name: '写作安排评分', max: 100 },
        { name: '逻辑构建评分', max: 100 },
        { name: '专业能力评分', max: 100 },
        { name: '学术规范评分', max: 100 },

      ],
      radius: '65%',
      splitNumber: 4,
      axisName: {
        color: '#333'
      },
      splitArea: {
        areaStyle: {
          color: ['rgba(255, 255, 255, 0.5)'],
          shadowColor: 'rgba(0, 0, 0, 0.2)',
          shadowBlur: 10
        }
      },
      axisLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.2)'
        }
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(0, 0, 0, 0.2)'
        }
      }
    },
    series: [{
      name: '能力评估',
      type: 'radar',
      data: []
    }]
  };

  chartInstance.setOption(option);
};

// 多折线图配置
const initMultiLineChart = () => {
  LineInstance = echarts.init(multiLineChart.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#6a7985'
        }
      }
    },
    legend: {
      data: [],
      bottom: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: []
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: []
  };
  LineInstance.setOption(option);
};


// 响应式调整图表大小
const resizeChart = () => {
  chartInstance?.resize();
  LineInstance?.resize();
};

onMounted(() => {
  getStudent();
  initRadarChart();
  initMultiLineChart();
  window.addEventListener('resize', resizeChart);
  input.value = '001';
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart);
  chartInstance?.dispose();
  LineInstance?.dispose();
});
</script>

<style scoped>
.sta-select {
  width: 200px;
  margin-top: 20px;
}
.id-select{
  display: flex;
  margin: 10px auto;
}
.id-input{
  width: 240px;
  height: 30px
}
.score-table{
  background-color: #f2f2f2;
  height: 130px;
}
.score{
  width: 95%;
  margin: 0 auto;
  background-color: #f2f2f2;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.score :deep(.el-table__header th) {
  text-align: center;
  color:#000000;
  background-color: #f2f2f2;
}
.score :deep(.el-table__body td) {
  text-align: center;
  background-color: #f2f2f2;
}
.score-compare{
  background-color: #f2f2f2;
  position: relative;
  top: 60px;
  border-radius: 4px;
  height: 500px;
}
.radar-chart {
  width: 95%;
  height: 400px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  position: relative;
  left: 30px;
}
.multi-line-chart {
  width: 95%;
  height: 400px;
  background: #f2f2f2;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  position: relative;
  left: 30px;
}
.new-score{
  font-size: 20px;
  padding: 10px;
}
.history-score{
  font-size: 20px;
  padding: 10px;
}
.paper-score{
  display: flex;
  justify-content: center;
  flex-direction: row;
  gap: 150px;
  text-align: center;
}
.total-title {
  font-size: 15px;
  margin: 10px;
}
.total-score{
  color:#7f7f7f
}
</style>